#!/usr/bin/env gosh
(use srfi-1)
(use sxml.ssax)
(use sxml.serializer)
(use sxml.tools)
(use sxml.sxpath)
(use sxml.tree-trans)
(use gauche.sequence)
(use gauche.process)
(use gauche.parseopt)

(define (run-cmd cmd values-list)
 (call-with-process-io
  cmd
  (lambda (in out)
    (for-each-with-index (lambda (i x)
			   (format out "~a\t~d\n" x i))
			 values-list)
    (flush out)
    (close-output-port out)
    (map (lambda (x)
	   (x->number (last (string-split x #\tab))))
	 (port->string-list in)))))

(define (main args)
  (define path-item (sxpath "//mark[@v]"))
  (define path-value (sxpath "//mark/@v/text()"))
  (let-args (cdr args)
      ((cmd  "c|cmd=s" "")
       (file "f|file=s" #f))
    (define sxml (if file
		   (call-with-input-file file (lambda (in)
						(ssax:xml->sxml in '())))
		   (ssax:xml->sxml (current-input-port) '())))
    (let ((items (path-item sxml)))
      (let ((items-contents (map sxml:content items))
	    (cmd-result (run-cmd cmd (path-value sxml))))
	(for-each (lambda (x place)
		    (sxml:change-content! x (list-ref items-contents place)))
		  items
		  cmd-result)))
    (print (srl:sxml->html (pre-post-order
			    sxml
			    `((mark . ,(lambda (x attr elems)
					 elems))
			      (*text* . ,(lambda (trigger x) x))
			      (*default* . ,(lambda x x))))))))
				







